﻿'         This file is Copyright © 2008-2012 Billy O'Neal and Aommaster
'                            All rights reserved.
'
' This file is released under the 2-Clause BSD license, included in LICENSE.TXT
'                           and on the MHWT website
Imports System.ComponentModel
Imports System.Text.RegularExpressions
Imports System.Environment
Imports System.IO

Friend Class FixForm
    Dim WithEvents speechDatabase As BindingList(Of Speech) = GlobalData.canDatabase
    Dim WithEvents editedTopic As Topic
    Public Sub New(ByVal TopicToEdit As Topic)
        editedTopic = TopicToEdit
        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        '
        'Close myself if the topic I'm editing is deleted.
        '
        AddHandler editedTopic.Deleted, AddressOf Me.Close
        populate()

    End Sub
    Private Sub populate() Handles editedTopic.Modified
        '
        'Deal with Can event handlers
        '
        For Each item As Object In fixList.Items
            Dim instanace As SpeechInstance = DirectCast(item, SpeechInstance)
            RemoveHandler instanace.Modified, AddressOf populate
        Next
        Try
            Me.fixList.Items.Clear()
        Catch ex As Exception

        End Try

        For Each item As SpeechInstance In editedTopic.Cans
            fixList.Items.Add(item)
            AddHandler item.Modified, AddressOf populate
        Next
        '
        'Deal with issue event handlers
        '
        For Each item As Object In issueListbox.Items
            Dim instanace As Issue = DirectCast(item, Issue)
            RemoveHandler instanace.Modified, AddressOf populate
        Next
        Me.issueListbox.Items.Clear()
        For Each item As Issue In editedTopic.Issues
            issueListbox.Items.Add(item)
            AddHandler item.Modified, AddressOf populate
        Next
        Me.Text = editedTopic.ToString()
        userNameBox.Text = editedTopic.Username
        linkBox.Text = editedTopic.Link
        logBox.Text = editedTopic.Log
        NotesBox.Text = editedTopic.Notes
        historycount.Text = editedTopic.totalhistory.ToString()

        'Populate history list box
        Dim historyarray() As String

        If editedTopic.History <> "" Then
            historyarray = editedTopic.History.Split(CChar("``"))

            treeview.Nodes.Clear()

            Dim PNode As New TreeNode
            For i = 1 To UBound(historyarray)
                If historyarray(i) <> "" Then
                    If CBool(InStr(historyarray(i), "*Fix")) Then
                        PNode = New TreeNode
                        PNode.Text = historyarray(i)
                        treeview.Nodes.Add(PNode)
                    Else
                        PNode.Nodes.Add(historyarray(i))
                    End If

                End If
            Next
        End If


    End Sub
    Private Sub addCan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addCan.Click, AddFixToolStripMenuItem.Click
        Dim childForm As New ChooseSpeech
        childForm.MdiParent = Me.MdiParent
        AddHandler childForm.FormClosed, AddressOf addCanReturn
        childForm.Show()
    End Sub
    Private Sub addCanReturn(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim chooser As ChooseSpeech = DirectCast(sender, ChooseSpeech)
        If Not chooser.returnedSpeech Is Nothing Then
            Dim editedInstance As New SpeechInstance(chooser.returnedSpeech)
            Dim childFrm As New EditSpeechInstance(editedInstance)
            childFrm.MdiParent = Me.MdiParent
            Me.editedTopic.Cans.Add(editedInstance)
            If childFrm.Visible Then childFrm.Show()
            editedTopic.modify()
        End If
    End Sub
    Private Sub editCan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editCan.Click, EditFixToolStripMenuItem.Click

        If fixList.SelectedItem IsNot Nothing Then
            For Each Fix As SpeechInstance In fixList.SelectedItems
                CType(Fix, SpeechInstance).TerminateEditor()
                Dim childFrm As New EditSpeechInstance(CType(Fix, SpeechInstance))
                childFrm.MdiParent = Me.MdiParent
                If childFrm.Visible Then childFrm.Show()
            Next

        Else
            MsgBox("Cant very well edit something that doesn't exist, can you?")
        End If
        editedTopic.modify()
    End Sub
    Private Sub delCan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delCan.Click, DeleteFixToolStripMenuItem.Click

        If fixList.SelectedItem IsNot Nothing Then
            Dim selected As System.Windows.Forms.ListBox.SelectedIndexCollection = fixList.SelectedIndices()
            Dim selectedarray(selected.Count() - 1) As Integer
            For i = 0 To UBound(selectedarray)
                selectedarray(i) = selected(i) - i
            Next

            For i = 0 To UBound(selectedarray)
                fixList.SelectedIndex = selectedarray(i)
                editedTopic.Cans.RemoveAt(fixList.SelectedIndex)
                editedTopic.modify()


            Next
        Else
            MsgBox("Cant very well delete something that doesn't exist, can you?")
        End If

    End Sub
    Private Sub canUpBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles canUpBtn.Click
        If fixList.SelectedItem Is Nothing Then Exit Sub
        Dim idxToInsert As Integer = fixList.SelectedIndex - 1
        If fixList.SelectedIndex <> 0 Then
            Dim temp As SpeechInstance = CType(fixList.SelectedItem, SpeechInstance)
            editedTopic.Cans.RemoveAt(fixList.SelectedIndex)
            editedTopic.Cans.Insert(idxToInsert, temp)
        End If
        editedTopic.modify()
        fixList.SelectedIndex = idxToInsert
    End Sub
    Private Sub canDownBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles canDownBtn.Click
        If fixList.SelectedItem Is Nothing Then Exit Sub
        Dim idxToInsert As Integer = fixList.SelectedIndex + 1
        If fixList.SelectedIndex <> (editedTopic.Cans.Count - 1) Then
            Dim temp As SpeechInstance = CType(fixList.SelectedItem, SpeechInstance)
            editedTopic.Cans.RemoveAt(fixList.SelectedIndex)
            editedTopic.Cans.Insert(idxToInsert, temp)
        End If
        editedTopic.modify()
        fixList.SelectedIndex = idxToInsert
    End Sub
    Private Sub outputTab_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles outputTab.Enter, previewTab.Enter
        Dim path As String = System.IO.Path.Combine(Environment.GetEnvironmentVariable("TEMP"), "preview.html")
        fixBox.Text = GlobalData.options.greeting + Environment.NewLine
        For Each instance As SpeechInstance In editedTopic.Cans
            If instance.SafeMode Then
                fixBox.Text += GlobalData.options.safeheader + Environment.NewLine
                Exit For
            End If
        Next
        For Each instance As SpeechInstance In editedTopic.Cans
            fixBox.Text += instance.Print()
        Next
        makelist()

        'preform replacements for username and nick
        fixBox.Text = Regex.Replace(fixBox.Text, "\[username]", userNameBox.Text, RegexOptions.IgnoreCase)
        'preform replacements for helper handle
        fixBox.Text = Regex.Replace(fixBox.Text, "\[helperhandle]", GlobalData.options.helperHandle, RegexOptions.IgnoreCase)

        'This handles [link] tags
        fixBox.Text = Regex.Replace(fixBox.Text, "\[link=([^\[]*)]([^\[]*)\[/link]", GlobalData.options.links.Replace("<target>", "$1").Replace("<text>", "$2"), RegexOptions.IgnoreCase)
        'Emphasis tags
        fixBox.Text = Regex.Replace(fixBox.Text, "\[emphasis]([^\[]*)\[/emphasis]", GlobalData.options.emphasis.Replace("<text>", "$1"), RegexOptions.IgnoreCase)
        'High emphasis tags
        fixBox.Text = Regex.Replace(fixBox.Text, "\[highemphasis]([^\[]*)\[/highemphasis]", GlobalData.options.hEmphasis.Replace("<text>", "$1"), RegexOptions.IgnoreCase)
        'Note tags
        fixBox.Text = Regex.Replace(fixBox.Text, "\[note]([^\[]*)\[/note]", GlobalData.options.note.Replace("<text>", "$1"), RegexOptions.IgnoreCase)
        'Unimportant tags
        fixBox.Text = Regex.Replace(fixBox.Text, "\[unimportant]([^\[]*)\[/unimportant]", GlobalData.options.unimportant.Replace("<text>", "$1"), RegexOptions.IgnoreCase)

        If InStr(sender.ToString(), "{Results}") = 0 Then
            Dim text As New BbCodeToHtmlFormatter
            text.StartConvert(fixBox.Text)
            previewbox.Url = New System.Uri(path)
            TabControl1.SelectTab(5)
        End If

    End Sub
    Private Sub userNameBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles userNameBox.TextChanged
        editedTopic.Username = userNameBox.Text
    End Sub
    Private Sub linkBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles linkBox.TextChanged
        editedTopic.Link = linkBox.Text
    End Sub
    Private Sub logBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles logBox.TextChanged
        editedTopic.Log = logBox.Text
    End Sub
    Private Sub notesBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NotesBox.TextChanged
        editedTopic.Notes = NotesBox.Text
    End Sub
    Private Sub FixForm_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        RemoveHandler editedTopic.Deleted, AddressOf Me.Close
        RemoveHandler editedTopic.Modified, AddressOf populate
        Dim fs As New IO.FileStream(System.IO.Path.Combine(Application.StartupPath, "Data.db"), IO.FileMode.Create)
        Dim formatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim temp As New DataFrontend
        formatter.Serialize(fs, temp)
        fs.Close()
    End Sub

    Private Sub cutButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cutButton.Click
        If logBox.SelectedText IsNot Nothing Then
            If logBox.SelectedText.Trim <> "" Then
                Clipboard.SetText(logBox.SelectedText)
                logBox.Text = logBox.Text.Remove(logBox.SelectionStart, logBox.SelectionLength)
            End If
        End If
    End Sub

    Private Sub copyButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles copyButton.Click
        If logBox.SelectedText IsNot Nothing Then
            If logBox.SelectedText.Trim <> "" Then
                Clipboard.SetText(logBox.SelectedText)
            End If
        End If
    End Sub

    Private Sub pasteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pasteButton.Click
        If Clipboard.ContainsText() Then
            logBox.Paste(Clipboard.GetText())
        End If
    End Sub

    Private Sub pasteWhole_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pasteWhole.Click
        If Clipboard.ContainsText() Then
            logBox.Text = Clipboard.GetText()
        End If
    End Sub

    Private Sub copyWhole_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles copyWhole.Click
        Clipboard.SetText(logBox.Text)
    End Sub

    Private Sub ihatewordwrapbtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ihatewordwrapbtn.Click
        '
        'We want to confirm because this will destroy logs that aren't from Hjt
        '
        If MsgBox("Are you sure?? Don't do this to anything other than a HJT log or it will DESTROY it!!", MsgBoxStyle.YesNo) = MsgBoxResult.No Then Exit Sub

        Dim completedString As String = "" 'Create a string to hold what's done
        Dim firstLineFound As Boolean = False
        Dim newlineAdded As Boolean = False
        Dim lines As New ArrayList
        lines.AddRange(logBox.Lines)
        For Each line As String In lines
            line.Trim(CChar(NewLine)) 'strip out all the newlines, we are going to add those by ourselves
            line.Trim() 'strip out whitespace
        Next
        For Each line As String In lines
            '
            'Header entries
            '
            If line.StartsWith("Scan saved at") Then completedString += NewLine
            If line.StartsWith("Platform:") Then completedString += NewLine
            If line.StartsWith("MSIE:") Then completedString += NewLine
            If line.StartsWith("Boot mode:") Then completedString += NewLine
            '
            'Running processes
            '
            If line.StartsWith("Running processes:") Then completedString += (NewLine + NewLine)
            If line.StartsWith("C:\") And Not firstLineFound Then completedString += NewLine '(Do not look for this if we are out of the running processes list)
            '
            'R Section
            '
            If line.StartsWith("R0 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("R1 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("R2 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("R3 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            '
            'F Section
            '
            If line.StartsWith("F0 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("F1 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            '
            'N Section
            '
            If line.StartsWith("N0 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("N1 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("N2 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("N3 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            '
            'O Section
            '
            If line.StartsWith("O1 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O2 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O3 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O4 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O5 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O6 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O7 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O8 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O9 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O10 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O11 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O12 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O13 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O14 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O15 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O16 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O17 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O18 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O19 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O20 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O21 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O22 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O23 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            If line.StartsWith("O24 - ") Then
                completedString += NewLine
                firstLineFound = True
            End If
            '
            'End of File
            '
            If line.StartsWith("--") Then completedString += (NewLine + NewLine)
            If line.StartsWith("End of file") Then completedString += NewLine
            '
            'The space between running processes and the other lines
            '
            If firstLineFound And Not newlineAdded Then
                newlineAdded = True
                completedString += NewLine
            End If
            '
            'Omit the line if it is blank
            '
            If line <> "" Then
                completedString += line
            End If
        Next
        logBox.Text = completedString
    End Sub

    Private Sub logNotes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles logNotes.Click
        If MsgBox("Are you sure? This will ERASE your notes!!", MsgBoxStyle.YesNo) = MsgBoxResult.No Then Exit Sub
        Dim finished As String = ""
        For Each line As String In logBox.Lines
            finished += line + NewLine + NewLine
        Next
        NotesBox.Text = finished
    End Sub

    Private Sub btnClearFix_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearFix.Click, ClearFixesToolStripMenuItem.Click
        If MsgBox("Are you sure you wish to clear this fix?", MsgBoxStyle.YesNo) = MsgBoxResult.No Then Exit Sub
        editedTopic.Cans.Clear()
        editedTopic.modify()
        editedTopic.Additionallogs = ""
    End Sub

    Private Sub CopyToClipboardToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyToClipboardToolStripMenuItem.Click
        Clipboard.SetText(fixBox.Text)
    End Sub

    Private Sub addIssueBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addIssueBtn.Click, AddIssueToolStripMenuItem.Click
        Dim newIssue As New Issue
        Dim child As New EditIssue(newIssue)
        child.MdiParent = Me.MdiParent
        editedTopic.Issues.Add(newIssue)
        child.Show()
        editedTopic.modify()
    End Sub

    Private Sub clearIssueBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles clearIssueBtn.Click, ClearIssuesToolStripMenuItem.Click
        If MsgBox("Are you sure you want to wipe issues?", MsgBoxStyle.YesNo) = MsgBoxResult.No Then Exit Sub
        editedTopic.Issues.Clear()
        editedTopic.modify()
    End Sub

    Private Sub editIssueBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editIssueBtn.Click, EditIssueToolStripMenuItem.Click

        If issueListbox.SelectedItem IsNot Nothing Then
            For Each selectedissue As Issue In issueListbox.SelectedItems
                Dim newIssue As Issue = DirectCast(selectedissue, Issue)
                Dim child As New EditIssue(newIssue)
                child.MdiParent = Me.MdiParent
                child.Show()
            Next

        Else
            MsgBox("The air is ~75% nitrogen... can't edit that!")
        End If
    End Sub
    Private Sub delIssueBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delIssueBtn.Click, DeleteIssueToolStripMenuItem.Click

        If issueListbox.SelectedItem IsNot Nothing Then
            Dim selected As System.Windows.Forms.ListBox.SelectedIndexCollection = issueListbox.SelectedIndices()
            Dim selectedarray(selected.Count() - 1) As Integer
            For i = 0 To UBound(selectedarray)
                selectedarray(i) = selected(i) - i
            Next

            For i = 0 To UBound(selectedarray)
                issueListbox.SelectedIndex = selectedarray(i)
                editedTopic.Issues.RemoveAt(issueListbox.SelectedIndex)
                editedTopic.modify()
            Next

        Else
            MsgBox("Considering you keep deleting stuff that doesn't exist.. I'm starting to think YOU are malware....")
        End If
    End Sub

    Private Sub createIssueContext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles createIssueContext.Click
        Dim startSelect As Integer
        startSelect = logBox.SelectionStart
        startSelect = logBox.Text.LastIndexOf(ControlChars.NewLine, startSelect)
        If startSelect = -1 Then startSelect = 0
        Dim endSelect As Integer
        endSelect = logBox.SelectionStart + logBox.SelectionLength
        endSelect = logBox.Text.IndexOf(ControlChars.NewLine, endSelect)
        If endSelect = -1 Then endSelect = 0
        Dim selected As String = logBox.Text.Substring(startSelect, endSelect - startSelect)
        Dim newIssue As New Issue
        newIssue.Evidence = selected.Trim()
        editedTopic.Issues.Add(newIssue)
        Dim child As New EditIssue(newIssue)
        child.MdiParent = Me.MdiParent
        child.Show()
        editedTopic.modify()
    End Sub

    Private Sub addtoissuebtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addtoissuebtn.Click
        Dim startSelect As Integer
        startSelect = logBox.SelectionStart
        startSelect = logBox.Text.LastIndexOf(ControlChars.NewLine, startSelect)
        If startSelect = -1 Then startSelect = 0
        Dim endSelect As Integer
        endSelect = logBox.SelectionStart + logBox.SelectionLength
        endSelect = logBox.Text.IndexOf(ControlChars.NewLine, endSelect)
        If endSelect = -1 Then endSelect = 0
        Dim selected As String = ControlChars.NewLine + logBox.Text.Substring(startSelect, endSelect - startSelect).Trim()
        Dim child As New PickIssue
        For Each item As Issue In issueListbox.Items
            child.cbIssues.Items.Add(item)
        Next
        If child.ShowDialog() = Windows.Forms.DialogResult.Cancel Then Exit Sub
        If child.cbIssues.SelectedItem Is Nothing Then Exit Sub
        DirectCast(child.cbIssues.SelectedItem, Issue).Evidence += selected
        Dim childIssueEditor As New EditIssue(DirectCast(child.cbIssues.SelectedItem, Issue))
        childIssueEditor.MdiParent = Me.MdiParent
        childIssueEditor.Show()
        editedTopic.modify()
    End Sub

    Private Sub bowsOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bowsOpen.Click
        editedTopic.browse()
    End Sub

    Private Sub markCloseWait_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles markCloseWait.Click
        editedTopic.Days = DateTime.Now.Date
        editedTopic.Status = "CloseWait"
        editedTopic.modify()
        Me.Close()
    End Sub

    Private Sub markStale_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles markStale.Click
        editedTopic.Status = "Stale"
        editedTopic.modify()
        Me.Close()
    End Sub

    Private Sub markDone_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles markDone.Click
        editedTopic.Status = "Completed"
        editedTopic.modify()
        Me.Close()
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        editedTopic.delete()
        GlobalData.openTopics.Remove(editedTopic)
        Me.Close()
    End Sub

    Private Sub fixList_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles fixList.DoubleClick
        If fixList.SelectedItem IsNot Nothing Then
            Dim childFrm As New EditSpeechInstance(CType(fixList.SelectedItem, SpeechInstance))
            childFrm.MdiParent = Me.MdiParent
            If childFrm.Visible Then childFrm.Show()
        End If
        editedTopic.modify()
    End Sub

    Private Sub issueListbox_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles issueListbox.DoubleClick
        If issueListbox.SelectedItem IsNot Nothing Then
            Dim newIssue As Issue = DirectCast(issueListbox.SelectedItem, Issue)
            Dim child As New EditIssue(newIssue)
            child.MdiParent = Me.MdiParent
            child.Show()
        End If
    End Sub

    Private Sub fixBox_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles fixBox.DoubleClick
        Clipboard.SetText(fixBox.Text)
        editedTopic.browse()
    End Sub

    Private Sub CopyAndOpenLinkToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyAndOpenLinkToolStripMenuItem.Click
        Clipboard.SetText(fixBox.Text)
        editedTopic.browse()
    End Sub

    Private Sub CopyOpenCloseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyOpenCloseToolStripMenuItem.Click
        Clipboard.SetText(fixBox.Text)
        editedTopic.browse()
        Me.Close()
    End Sub

    Private Sub CopyOpenCloseWaitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyOpenCloseWaitToolStripMenuItem.Click
        Clipboard.SetText(fixBox.Text)
        editedTopic.browse()
        editedTopic.Status = "CloseWait"
        editedTopic.modify()
        Me.Close()
    End Sub

    Private Sub CopyOpenStaleToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyOpenStaleToolStripMenuItem.Click
        Clipboard.SetText(fixBox.Text)
        editedTopic.browse()
        editedTopic.Status = "Stale"
        editedTopic.modify()
        Me.Close()
    End Sub

    Private Sub CopyOpenCompletedToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyOpenCompletedToolStripMenuItem.Click
        Clipboard.SetText(fixBox.Text)
        editedTopic.browse()
        editedTopic.Status = "Completed"
        editedTopic.modify()
        Me.Close()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        editedTopic.Days = DateTime.Now.Date
        editedTopic.Status = "" '0 day(s)
    End Sub

    Private Sub DeleteFixToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteFixToolStripMenuItem.Click
        If fixList.SelectedItem IsNot Nothing Then
            DirectCast(fixList.SelectedItem, SpeechInstance).TerminateEditor()
            editedTopic.Cans.RemoveAt(fixList.SelectedIndex)
        Else
            MsgBox("Cant very well delete something that doesn't exist, can you?")
        End If
        editedTopic.modify()
    End Sub

    Private Sub CopySelectedTextToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopySelectedTextToolStripMenuItem.Click
        If fixBox.SelectedText <> "" Then
            Clipboard.SetText(fixBox.SelectedText)
        Else
            MsgBox("Can't copy something that doesn't exist, can I?")
        End If

    End Sub

    Private Sub AddLogs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddLogs.Click

        Dim childfrm As New AddLogs(editedTopic.Additionallogs)
        childfrm.MdiParent = Me.MdiParent
        childfrm.Show()
        AddHandler childfrm.FormClosed, AddressOf updateadditionallogs


    End Sub
    Private Sub updateadditionallogs(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim childfrm As AddLogs = DirectCast(sender, AddLogs)
        editedTopic.Additionallogs = childfrm.AdditionalLogsBox.Text
    End Sub
    Private Sub makelist()
        Dim tempLogList As New List(Of String)
        For Each instance As SpeechInstance In editedTopic.Cans
            For Each log As String In instance.logs
                tempLogList.Add("[*]" + log.Trim())
            Next
        Next
        If tempLogList.Count <> 0 Or Trim(editedTopic.Additionallogs).Length <> 0 Then
            Dim Header As String
            Dim Footer As String
            Dim position As Integer
            position = InStr(GlobalData.options.logform, "<list>")
            If position = 0 Then
                position = 1
                Header = "[list]"
                Footer = "[/list]"
            Else
                Header = GlobalData.options.logform.Substring(0, (position - 1)) & "[list]"
                Footer = GlobalData.options.logform.Substring((position + 5), (GlobalData.options.logform.Length - (position + 5)))
            End If

            Dim loglist As String = ""

            fixBox.Text += Header
            If tempLogList.Count <> 0 Then
                For Each log As String In tempLogList
                    If InStr(loglist, log) = 0 Then
                        loglist += log
                    End If

                Next
            End If

            If Trim(editedTopic.Additionallogs).Length <> 0 Then
                Dim addedlogs() As String = editedTopic.Additionallogs.Split(CChar(Environment.NewLine))
                For i = 0 To UBound(addedlogs)
                    If InStr(loglist, addedlogs(i).Trim()) = 0 Then
                        loglist += "[*]" + addedlogs(i).Trim()
                    End If
                Next

            End If
            fixBox.Text += loglist
            fixBox.Text += "[/list]" & Footer
        End If
        fixBox.Text += GlobalData.options.signature

    End Sub

    Private Sub addhistory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addhistory.Click
        If fixList.Items.Count <> 0 Then
            Dim tempstring As String = ""
            editedTopic.totalhistory += 1
            historycount.Text = editedTopic.totalhistory.ToString()

            For Each item As Object In fixList.Items
                tempstring += "``" + item.ToString()
            Next

            editedTopic.History += "``" + "*Fix " + editedTopic.totalhistory.ToString() + tempstring
            editedTopic.modify()
            Dim historyarray() As String
            treeview.Nodes.Clear()

            historyarray = editedTopic.History.Split(CChar("``"))

            Dim PNode As New TreeNode
            For i = 1 To UBound(historyarray)
                If historyarray(i) <> "" Then
                    If CBool(InStr(historyarray(i), "*Fix")) Then
                        PNode = New TreeNode
                        PNode.Text = historyarray(i)
                        treeview.Nodes.Add(PNode)
                    Else
                        PNode.Nodes.Add(historyarray(i))
                    End If

                End If
            Next
            MsgBox("Current speech list added")
        Else
            MsgBox("Nothing to add!")
        End If



    End Sub
    Private Sub clearhistory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles clearhistory.Click
        editedTopic.totalhistory = 0
        editedTopic.History = ""
        editedTopic.modify()
        historycount.Text = editedTopic.totalhistory.ToString()
        treeview.Nodes.Clear()
    End Sub
    Private Sub deletehistory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletehistory.Click
        Dim retvalue As Integer = 0
        Dim noselection As Integer = 0

        If editedTopic.totalhistory > 0 Then
            retvalue = MsgBox("Are you sure you want to delete this entire fix?", MsgBoxStyle.YesNo, "Deleting Fix from history")
            If retvalue = 6 Then
                Dim indextodelete As Integer = 0



                Dim history As String = editedTopic.History
                Dim fixtoremove As String = ""
                Dim fixvalstart As Integer = 0
                Dim fixvalend As Integer = 0


                Try
                    indextodelete = treeview.SelectedNode.Parent.Index
                Catch ex1 As Exception
                    Try
                        indextodelete = treeview.SelectedNode.Index
                    Catch ex2 As Exception
                        MsgBox("No fix selected")
                        noselection = 1
                    End Try

                End Try
                If noselection <> 1 Then
                    fixvalstart = InStr(history, "*Fix " + (indextodelete + 1).ToString())
                    fixvalend = InStr(history, "*Fix " + (indextodelete + 2).ToString())

                    If fixvalend <> 0 Then
                        history = history.Substring(0, fixvalstart - 2) + history.Substring(fixvalend - 2, history.Length - fixvalend + 2)
                    Else
                        history = history.Substring(0, fixvalstart - 2)
                    End If

                    editedTopic.totalhistory -= 1

                    For i = indextodelete + 1 To treeview.Nodes.Count
                        history = Replace(history, "*Fix " + i.ToString(), "*Fix " + (i - 1).ToString(), , 1)
                    Next

                    historycount.Text = editedTopic.totalhistory.ToString()
                    editedTopic.History = history



                    Dim historyarray() As String
                    treeview.Nodes.Clear()

                    historyarray = editedTopic.History.Split(CChar("``"))

                    Dim PNode As New TreeNode
                    For i = 1 To UBound(historyarray)
                        If historyarray(i) <> "" Then
                            If CBool(InStr(historyarray(i), "*Fix")) Then
                                PNode = New TreeNode
                                PNode.Text = historyarray(i)
                                treeview.Nodes.Add(PNode)
                            Else
                                PNode.Nodes.Add(historyarray(i))
                            End If

                        End If
                    Next
                End If

            End If
        Else
            MsgBox("Nothing existed before the Big Bang...")
        End If
    End Sub
End Class